//
//  BgoodsrightViewController.m
//  Distributor
//
//  Created by 主事丫环 on 2019/5/16.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "BgoodsrightViewController.h"
#import "BgoodsAdmimTableViewCell.h"
#import "BgoodsAdminListModel.h"
#import "BEditShopDetaileViewController.h"

@interface BgoodsrightViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *myTableView;
@property(nonatomic,strong)NSMutableArray *mydateSource;
@property(nonatomic,assign)NSInteger dayind;

@end

@implementation BgoodsrightViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
    
    self.mydateSource = [NSMutableArray arrayWithCapacity:1];
    [self.myTableView reloadData];
    
    [self request];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refashaction:) name:@"refashB" object:nil];
    // Do any additional setup after loading the view.
}

-(void)refashaction:(NSNotification *)noti{
    [self request];
}

-(void)request{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    [NetWorkTool POST:BcellProdctList param:param success:^(id dic) {
        [self.mydateSource removeAllObjects];
        for (NSMutableDictionary *mudic in [dic objectForKey:@"data"]) {
            [DYModelMaker DY_makeModelWithDictionary:mudic modelKeyword:@"" modelName:@""];
            BgoodsAdminListModel *model = [[BgoodsAdminListModel alloc]init];
            [model setValuesForKeysWithDictionary:mudic];
            if ([model.product_state integerValue] == 2) {
                [self.mydateSource addObject:model];
            }
            //1上架
        }
        [self.myTableView reloadData];
        NSString *label = [NSString stringWithFormat:@"%lu",(unsigned long)self.mydateSource.count];
        NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:label,@"one", nil];
        NSNotification *notification =[NSNotification notificationWithName:@"tongzhiright" object:nil userInfo:dict];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        [self.mydateSource removeAllObjects];
        [self.myTableView reloadData];
        
    } fail:^(NSError *error) {
        [self.mydateSource removeAllObjects];
        [self.myTableView reloadData];

    } needUser:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.mydateSource.count;;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return 114;
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BgoodsAdmimTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BgoodsAdmimTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BgoodsAdminListModel *model = [_mydateSource safeObjectAtIndex:indexPath.row];
    [cell refash:model];
    kWeakSelf;
    cell.myblock = ^(NSInteger ind) {
        if (ind == 1) {
            //上架
            [self xiajiaAction:model];
        } else if (ind == 2){
            //编辑
            BEditShopDetaileViewController *edit = [[BEditShopDetaileViewController alloc]init];
            edit.mymodel = model;
            [weakSelf.navigationController pushViewController:edit animated:YES];
        } else if (ind == 0){
            //删除
            [self shanchu:model];
        }
    };
    return cell;
}

-(void)shanchu:(BgoodsAdminListModel *)model{
    
    UIAlertController *alertCon = [UIAlertController alertControllerWithTitle:@"确定现在发货？" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertCon addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        KMyLog(@"取消");
    }]];
    [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        KMyLog(@"确定");
        
        NSMutableDictionary *mudic = [NSMutableDictionary dictionaryWithCapacity:1];
        mudic[@"id"] = NOTNIL(model.Id);
        
        NSString *jsonstr = [HFTools toJSONString:mudic];
        NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
        param [@"data"] = jsonstr;
        
        kWeakSelf;
        [NetWorkTool POST:BshopdeleteProdct param:mudic success:^(id dic) {
            //ShowToastWithText(@"删除成功");
            [self showOnlePicText:@"删除成功" delay:1.5];
            [weakSelf request];
            //[[NSNotificationCenter defaultCenter] postNotificationName:@"refashA" object:nil];
        } other:^(id dic) {
            ShowToastWithText(dic[@"msg"]);
        } fail:^(NSError *error) {
            
        } needUser:YES];
    }]];
    [self presentViewController:alertCon animated:YES completion:nil];
}

-(void)xiajiaAction:(BgoodsAdminListModel *)model{
    NSMutableDictionary *mudic = [NSMutableDictionary dictionaryWithCapacity:1];
    [self showOnlePicText:@"上架成功" delay:1.5];

    mudic[@"product_state"] = @"1";
    mudic[@"id"] = NOTNIL(model.Id);
    
    NSString *jsonstr = [HFTools toJSONString:mudic];
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param [@"data"] = jsonstr;
    
    kWeakSelf;
    [NetWorkTool POST:BupdateCellProdct param:param success:^(id dic) {
        //ShowToastWithText(@"上架成功");
        [self showOnlePicText:@"上架成功" delay:1.5];
        [weakSelf request];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refashA" object:nil];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
}

-(NSDate *)nsstringConversionNSDate:(NSString *)dateStr{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *datestr = [dateFormatter dateFromString:dateStr];
    return datestr;
}

-(NSString *)dateConversionTimeStamp:(NSDate *)date{
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]*1000];
    return timeSp;
}

- (BOOL)timeAgoWithDatedfdsfsf:(NSString*)date{
    
    date = [NSString stringWithFormat:@"%@",date];
    
    NSString *datrStr = [NSString stringWithFormat:@"%@",date];
    NSString*time =[datrStr substringToIndex:datrStr.length-3];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyy-MM-dd HH:mm:ss"];
    NSDate*confromTimesp = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[time intValue]];
    
    double deltaSeconds = fabs([confromTimesp timeIntervalSinceDate:[NSDate date]]);
    double deltaMinutes = deltaSeconds / 60.0f;
    
    if (deltaMinutes < (24 * 60 * self.dayind)){
        //int day = (int)floor(deltaMinutes/(60 * 24));
        return YES;
    } else {
        return NO;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BgoodsAdminListModel *model = [_mydateSource safeObjectAtIndex:indexPath.row];
    BEditShopDetaileViewController *edit = [[BEditShopDetaileViewController alloc]init];
    edit.mymodel = model;
    [self.navigationController pushViewController:edit animated:YES];
}

-(UITableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT-kNaviHeight-60) style:(UITableViewStylePlain)];
        _myTableView.backgroundColor = [UIColor clearColor];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableView.estimatedRowHeight = 90;
        _myTableView.rowHeight = UITableViewAutomaticDimension;
        _myTableView.tableFooterView = [UIView new];
        //_myTableView.placeHolderView = [[KKTableViewNoDataView alloc]initWithFrame:_myTableView.bounds image:imgname(@"tableviewPlaseholder") viewClick:^{
        //    [_myTableView.mj_header beginRefreshing];
        //}];
        [_myTableView registerNib:[UINib nibWithNibName:@"BgoodsAdmimTableViewCell" bundle:nil] forCellReuseIdentifier:@"BgoodsAdmimTableViewCell"];
        adjustInset(_myTableView);
        [self.view addSubview:_myTableView];
    }
    return _myTableView;
}

@end
